﻿package net.wangit.dev.version;

import java.util.ArrayList;
import java.util.List;

import net.wangit.LabelUtil;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionResult;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.etl.ETLUtil;
import net.wangit.support.Action;
import net.wangit.util.Checker;


public class OutputVersionAction implements Action {

	public OutputVersionAction() {
	}

	public ActionContext execute(ActionContext ac) throws Exception {
		ActionResult result = ac.getActionResult();
		List<String> ids = getIds(ac);
		if (Checker.isEmpty(ids)) {
			result.addInfo(LabelUtil.get(ac, "dev", "output.unselected"));
			return ac;
		}
		int outputMode = ac.getRequestParameterInt("output.outputmode", 2);
		int type = ac.getRequestParameterInt("output.type", 2);
		String domain = ConsoleDomainUtil.getDomain(ac);
		String batchId = ETLUtil.getBatchId(ac);
		try {
			Version version = VersionFactory.getVersion(type);
			version.save(outputMode, domain, batchId, ids);
			String array[] = { Integer.toString(ids.size()), batchId };
			result.addInfo(LabelUtil.get(ac, "dev", "output.1", array));
		} catch (Exception e) {
			result.setSuccessful(false);
			result.addError(LabelUtil.get(ac, "dev", "output.0"));
			throw e;
		}
		return ac;
	}

	public List<String> getIds(ActionContext ac) {
		String checks[] = ac.getRequestParameters("_treecheck");
		if (Checker.isEmpty(checks))
			return null;
		List<String> ids = new ArrayList<String>();
		for (int i = 0; i < checks.length; i++)
			if (!"-".equals(checks[i]))
				ids.add(checks[i].substring(4));

		return ids;
	}
}
